package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            //分析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            //处理请求
            String path = request.getUri();
            File rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            File staticDir = new File(rootDir,"static");
            File file = new File(staticDir,path);
            System.out.println("该资源文件是否存在：" + file.exists());
            String line;
            if (!file.isFile()) {
//                line = "HTTP/1.1 404 NotFound";
                file = new File(staticDir, "/root/404.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
            }
            response.setContentFile(file);

            //发送响应
            response.response();

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
